<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${!dataId || isCopy ? '新增' : '编辑'}-工艺模版`"
		width="1100px"
		:append-to-body="false"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" :show-message="false">
			<el-row ref="box1">
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="编号">
						<span class="read-only-2">{{ ruleForm.code || '系统自动生成' }}</span>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="工序" prop="processId">
						<jk-select v-model="ruleForm.processId" :option-list="processList" size="medium" placeholder="工序" clearable class="width-100-percent" @change="onProcessChange"></jk-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="机型" prop="machineModelId">
						<jk-select v-model="ruleForm.machineModelId" :disabled="!ruleForm.processId" :option-list="machineModelList" size="medium" placeholder="机型" clearable class="width-100-percent" @change="onModelChange"></jk-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="纺纱方式" prop="spinTypeId">
						<jk-select v-model="ruleForm.spinTypeId" :option-list="spinTypeList" size="medium" placeholder="纺纱方式" clearable class="width-100-percent"></jk-select>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<div class="margin-bottom-4">
			<jk-button :disabled="!ruleForm.processCode || !ruleForm.spinTypeId || !ruleForm.machineModelId" size="mini" type="primary" icon="el-icon-plus" class="item-gap" @click="onAddBtn">添加项目</jk-button>
		</div>
		<jk-table ref="jkTable" border :data="ruleForm.itemList || []" :max-height="dialogTableHeight - 30">
			<vxe-column width="60" align="center">
				<template #default>
					<div class="drag-btn"><i class="el-icon-rank"></i></div>
				</template>
				<template #header>
					<el-popover title="提示" content="双击拖动调整顺序！" placement="bottom" trigger="hover">
						<i slot="reference" class="el-icon-info drag-info-icon"></i>
					</el-popover>
				</template>
			</vxe-column>
			<vxe-column title="操作" align="center" field="operation" :width="110">
				<template slot-scope="scope">
					<div class="flex-center">
						<jk-button size="mini" icon="el-icon-plus" class="item-gap" @click="onAddBtn(scope.rowIndex)"></jk-button>
						<jk-button size="mini" icon="el-icon-minus" @click="ruleForm.itemList.splice(scope.rowIndex, 1)"></jk-button>
					</div>
				</template>
			</vxe-column>
			<vxe-column title="序号" align="center" type="seq" :width="70"></vxe-column>
			<vxe-column title="项目名称" align="left" field="itemName" :width="160">
				<template slot-scope="scope">
					<jk-input v-model="scope.row.itemName" placeholder="项目名称" size="mini"></jk-input>
				</template>
			</vxe-column>
			<vxe-column title="数据类型" align="center" field="dataType" :width="180">
				<template slot-scope="scope">
					<el-radio-group v-model="scope.row.dataType">
						<el-radio :label="1">数字</el-radio>
						<el-radio :label="2">字符</el-radio>
					</el-radio-group>
				</template>
			</vxe-column>
			<vxe-column title="采集点位" align="left" field="signalList" :width="180">
				<template slot-scope="scope">
					<itemSignalList
						class="width-100-percent"
						:form-data="ruleForm"
						:option-list="scope.row.signalList || []"
						@on-confirm="setData($event, scope.rowIndex)"
					></itemSignalList>
				</template>
			</vxe-column>
			<vxe-column title="角色" align="center" field="roleIds" :min-width="200">
				<template #header>
					<el-popover title="提示" content="" placement="bottom" trigger="click">
						<jk-select v-model="roleIds" :collapse-tags="true" :multiple-limit="20" multiple class="width-100-percent" :option-list="roleList" @change="onRoleChange"></jk-select>
						<div slot="reference" class="drag-info-icon" style="color: #2d8cf0;font-size: 13px;">角色 <span class="el-icon-edit"></span></div>
					</el-popover>
				</template>
				<template slot-scope="scope">
					<jk-select v-model="scope.row.roleIds" :collapse-tags="true" :multiple-limit="20" multiple class="width-100-percent" :option-list="roleList"></jk-select>
				</template>
			</vxe-column>
		</jk-table>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import {
        spinSpecProjectPage,
        spinTechnologyModelCreate,
        spinTechnologyModelGet, spinTechnologyModelUpdate
    } from '../../../api/technology/item';
    import { systemBusinessDictPage } from '../../../api/basicData/businessDict';
    import Sortable from 'sortablejs';
    import {
        spinMachineModelPage
    } from '../../../api/basicData/machineModel';
    import { listRole } from '../../../api/system/role';
    import itemSignalList from './components/item-signal-list';
    export default {
        name: 'TechnologyItem',
        components: {
            itemSignalList
        },
        mixins: [calHeight],
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            isCopy: { // 是否复制
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        data() {
            return {
                roleIds: [],
                tableLoading: false,
                spinMachineModelPage: [],
                processList: [],
                saveBtnLoading: false,
                workshopList: [],
                machineModelList: [],
                spinTypeList: [],
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                saveDialogState: false,
                ruleForm: {
                    'auditState': 0,
                    'code': '',
                    'itemList': [],
                    'machineModelCode': '',
                    'machineModelId': null,
                    'machineModelName': '',
                    'processCode': '',
                    'processId': null,
                    'processName': '',
                    'remark': '',
                    'spinTypeCode': '',
                    'spinTypeId': null,
                    'spinTypeName': ''
                },
                rules: {
                    machineModelId: [{ required: true, trigger: 'change' }],
                    paramType: [{ required: true, trigger: 'change' }],
                    processId: [{ required: true, trigger: 'change' }],
                    code: [{ required: true, trigger: 'change' }],
                    spinTypeId: [{ required: true, trigger: 'change' }]
                },
                defaultRowItem: {
                    'dataType': 1,
                    'id': null,
                    'itemCode': '',
                    'itemId': null,
                    'itemName': '',
                    'sortNum': null
                },
                roleList: []
            };
        },
        methods: {
            setData(e, index) {
                this.$set(this.ruleForm.itemList[index], 'signalList', e);
            },
            onRoleChange(e) {
                this.ruleForm.itemList.forEach(x => {
                    x.roleIds = e;
                });
            },
            onModelChange() {
                this.ruleForm.itemList.forEach(x => {
                    x.signalList = [];
                });
            },
            onProcessChange(e) {
                const item = this.processList.find(x => x.id === e) || {};
                this.$set(this.ruleForm, 'processCode', item.code);
                this.$set(this.ruleForm, 'processName', item.name);
                this.$set(this.ruleForm, 'machineModelId', null);
                this.$set(this.ruleForm, 'machineModelCode', '');
                this.$set(this.ruleForm, 'machineModelName', '');
                // this.$set(this.ruleForm, 'itemList', []);
                if (this.ruleForm.processId) {
                    this.getMachineModelListRequest();
                    spinSpecProjectPage({
                        auditState: 1,
                        processId: this.ruleForm.processId,
                        pageNo: 1,
                        pageSize: 100
                    }).then(res => {
                        if (res.data.status === 200) {
                            if (res.data.res && res.data.res.length === 1) {
                                const arr = res.data.res[0].itemList || [];
                                arr.forEach(x => {
                                    delete x.id;
                                });
                                // this.$set(this.ruleForm, 'itemList', arr);
                            }
                        }
                    });
                }
            },
            loadSortTable() {
                this.$nextTick(() => {
                    const xTable = this.$refs.jkTable.$refs.xTable;
                    this.sortable1 = Sortable.create(xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
                        handle: '.drag-btn',
                        animation: 500,
                        onEnd: ({ newIndex, oldIndex }) => {
                            const currRow = this.ruleForm.itemList.splice(oldIndex, 1)[0];
                            this.ruleForm.itemList.splice(newIndex, 0, currRow);
                        }
                    });
                });
            },
            onIotChange(e) {
                if (e) {
                    const iotItem = this.machineModelList.find(x => x.typeId === e) || {};
                    this.$set(this.ruleForm, 'dataType', iotItem.dataType);
                } else {
                    this.$set(this.ruleForm, 'dataType', 1);
                }
            },
            onAddBtn(index) {
                if (index || index === 0) {
                    this.ruleForm.itemList.splice(index + 1, 0, JSON.parse(JSON.stringify(this.defaultRowItem)));
                } else {
                    this.ruleForm.itemList.push(JSON.parse(JSON.stringify(this.defaultRowItem)));
                }
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (!this.dataId || this.isCopy) delete params.id;
                const processItem = this.processList.find(x => x.id === params.processId) || {};
                params.processCode = processItem.code;
                params.processName = processItem.name;

                const spinTypeItem = this.spinTypeList.find(x => x.id === params.spinTypeId) || {};
                params.spinTypeCode = spinTypeItem.code;
                params.spinTypeName = spinTypeItem.name;

                const machineModelItem = this.machineModelList.find(x => x.id === params.machineModelId) || {};
                params.machineModelCode = machineModelItem.code;
                params.machineModelName = machineModelItem.name;

                let arr = [];
                params.itemList.forEach(x => {
                    if (this.isCopy) delete x.id;
                    arr = x.roleIds ? this.roleList.filter(k => x.roleIds.includes(k.id)) : [];
                    x.roleList = arr.map(j => {
                        return {
                            'id': j.id,
                            'code': j.code,
                            'name': j.name
                        };
                    });
                });

                return params;
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                // ID不存在或isCopy为true时使用"创建"接口
                const api = !this.dataId || this.isCopy ? spinTechnologyModelCreate : spinTechnologyModelUpdate;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return spinTechnologyModelGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        if (resData.itemList) {
                            resData.itemList.forEach(x => {
                                x.roleIds = x.roleList ? x.roleList.map(x => x.id) : [];
                            });
                        }
                        if (this.isCopy) {
                            resData.auditState = 0;
                            resData.code = '';
                        }
                        this.ruleForm = resData;
                    }
                });
            },
            getMachineModelListRequest() {
                if (!this.ruleForm.processId) return;
                return spinMachineModelPage({
                    auditState: 1,
                    processId: this.ruleForm.processId
                }).then(res => {
                    if (res.data.status === 200) {
                        this.machineModelList = res.data.res || [];
                    }
                });
            },
            getSpinTypeListRequest() {
                return systemBusinessDictPage({ categoryCode: 'SPIN_TYPE' }).then(res => {
                    if (res.data.status === 200) {
                        this.spinTypeList = res.data.res || [];
                    }
                });
            },
            getRoleListRequest() {
                return listRole().then(res => {
                    if (res.data.status === 200) {
                        this.roleList = res.data.res || [];
                    }
                });
            },
            async getDependentData() {
                this.processList = this.$store.state.user.userProcess.processList;
                this.showLoading = true;
                await this.getRoleListRequest();
                await this.getSpinTypeListRequest();
                if (this.dataId) await this.getDetailRequest();
                await this.getMachineModelListRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.loadSortTable();
                    this.getDependentData();
                }
            }
        }
    };
</script>
<style scoped lang="scss">
.drag-info-icon {
    font-size: 14px;
}
.drag-btn {
    cursor: move;
    color: #2d8cf0;
    transition: all .5s;
    font-size: 18px;
}
.drag-btn:hover {
    //transform: rotate(90deg);
}
</style>
